package org.yty.travelagencyredis.Dao.impl;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.yty.travelagencyredis.Dao.TravellerDao;
import org.yty.travelagencyredis.model.Entity.Traveller;

import java.util.Collections;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class TravellerDaoImpl implements TravellerDao {
    private final StringRedisTemplate redisTemplate;

    @Override
    public Traveller selectById(Long id) {
         String travellerJson = (String) this.redisTemplate.opsForHash().get(Traveller.key, id);
         if (travellerJson == null){
             return null;
         }
         return JSON.parseObject(travellerJson, Traveller.class);
    }

    @Override
    public boolean insert(Traveller traveller) {
        this.redisTemplate.opsForHash().put(Traveller.key, traveller.getId(), JSON.toJSONString(traveller));
        return true;
    }

    @Override
    public boolean save(Traveller traveller) {
        this.redisTemplate.opsForHash().put(Traveller.key, traveller.getId(), JSON.toJSONString(traveller));
        return true;
    }

    @Override
    public void deleteById(Long id) {
        this.redisTemplate.opsForHash().delete(Traveller.key, id);
    }

    @Override
    public List<Traveller> getListByIdList(List<Long> travellerIdList) {
        List<Object> list = this.redisTemplate.opsForHash().multiGet(Traveller.key, Collections.singleton(travellerIdList));
        return list.stream().map(item -> JSON.parseObject((String) item, Traveller.class)).toList();
    }
}
